<template>
	<view class="">
		<view class="cart_con" v-if="cartList.length>0">
			<view class="cart_manager">
				<view class="cart_managerleft">
					<image class="cart_managerimg" src="https://img-cdn.duobashuzi.com/xianggui/img/dianpu.png"
						mode="widthFix"></image>
					<text>康源生活</text>
					<image class="cart_managerimg" src="https://img-cdn.duobashuzi.com/xianggui/img/right.png"
						mode="widthFix"></image>
				</view>
				<span @click="handleManager">{{managerText}}</span>
			</view>
			<view class="cart_list">
				<u-swipe-action>
					<u-swipe-action-item @click="chufa()" :options="item.options" v-for="(item, index) in cartList"
						:key="item.cart_id" :name="index">
						<view class="swipe-action">
							<view class="swipe-action__content">
								<view class="cart_item">
									<view class="cart_left" @click="handleSelect(item)">
										<image v-show="item.isSelect == 1" src="https://img-cdn.duobashuzi.com/xianggui/img/select-cart.png"
											mode="widthFix"></image>
										<image v-show="item.isSelect != 1" src="https://img-cdn.duobashuzi.com/xianggui/img/no-select.png" mode="widthFix">
										</image>
									</view>
									<view class="cart_right">
										<view class="cart_img" @click="jump(item.product_id,item.product_name)">
											<image :src="item.preview_img" mode="widthFix"></image>
										</view>
										<view class="cart_info">
											<view class="cart_name">
												{{item.product_name}}
											</view>
											<view class="cart_huiy"  v-if="user_level != 0">
												<text>会员价</text>
											</view>
											<view class="cart_tishi" v-else>{{item.member_msg}}</view>	
											<block v-if="item.dimensions">
												<view class="cart_guige" @click="getGoods(item.product_id,item.cart_id)">
													
													<text>{{item.dimensions}}</text>
													<image src="https://img-cdn.duobashuzi.com/xianggui/img/jts.png"mode="widthFix"></image>
												</view>
											</block>
											
											<!-- <view class="cart_tishi">比加入时便宜5.31元</view> -->
											<view class="cart_in_bottom">
												<view class="cart_price">
													
													<view class="cart_price1"><text>￥</text>{{item.local_shop_price}}
													</view>
													<view class="cart_price2"><text>￥</text>{{item.cart_market_price}}
													</view>
												</view>
												<view class="cart_num">
													<!-- <u-number-box v-model="value" @change="valChange"></u-number-box> -->
													<u-number-box @change="changeNum" :asyncChange="true"
														:name="item.cart_id" :value="item.number" min="1">

													</u-number-box>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>

			</view>
			
			<!-- 底部结算 -->
			<view class="set_money" v-show="isSetmoney">
				<div class="selectAll" @click="toggleSelectAll">
					<image v-if="isAllSelected" src="https://img-cdn.duobashuzi.com/xianggui/img/select-cart.png" mode="widthFix"></image>
					<image v-else src="https://img-cdn.duobashuzi.com/xianggui/img/no-select.png" mode="widthFix"></image>
					<span>全选</span>
				</div>
				<view class="set_money_con" v-if="!isManager">
					<view class="money_count">
						<view class="moneytop">
							<text class="yunfei">不含运费</text>合计：
							<text class="red qian">￥{{total}}</text>
						</view>
						<view class="moneybot">
							
							<view class="moneybotleft"  v-if="user_level == 1">共优惠：￥{{totaltwo}}</view>
							<view class="moneybotleft"  v-else>共优惠：￥0.00</view>
							<view class="moneybotright" @click="onisDetailed">优惠明细<image :class="['yhmx',{xuanzhuan:isDetailed}]" src="https://img-cdn.duobashuzi.com/xianggui/img/jts.png"
						mode="widthFix"></image></view>
						</view>
						
					</view>
					<view class="money_btn" v-if="isCheckoutEnabled" @click="handleSave">
						去结算
					</view>
					<view class="money_btn huise" v-else>
						去结算
					</view>
				</view>
				<view v-else class="set_delete">
					<view class="delete_btn" v-if="isCheckoutEnabled" @click="handleDelete">删除</view>
					<view class="delete_btn huise" v-else>删除</view>
				</view>
			</view>
		</view>
		<!-- 空的购物车-->
		<view class="" v-else>
			<u-empty mode="car" icon="https://img-cdn.duobashuzi.com/xiangguijia/v1/car.png">
			</u-empty>
			<view class="zanwusts">您可以选择喜欢的商品加入购物车</view>
			<view class="zanwus">
				<view class="zanwusBut">
					<view class="bot botright" @click="fhsy">前往选购</view>
				</view>
			</view>
		</view>
		
		<view id="recommend"  class="recommendli">
			<u-divider text="更多个性化推荐"></u-divider>
			<sheet-recommend :isType.sync="isType" ref="getXgjgoodlist"></sheet-recommend>
		</view>
		<view class="kong"></view>
		<!-- 优惠明细 -->
		<u-popup :show="isDetailed" :round="20" mode="bottom" @close="closeDetailed" @open="open">
			<view>
				<view class="dtailed">
					<view class="gunabi" @click="closeDetailed" ><image src="https://img-cdn.duobashuzi.com/xianggui/img/gunabi.png" mode="scaleToFill"></image></view>
					<view class="dtailedTop">优惠明细</view>
					<view class="dtailedCont">
						<view class="dtailedeli">
							<text>商品总额</text>
							<text>￥{{total}}</text>
						</view>
						<view class="dtailedeli">
							<text>共优惠</text>
							<text class="red">-￥0.00</text>
						</view>
						<view class="dtailedeli huises" v-if="user_level == 1">
							<text>会员折扣</text>
							<text>-￥{{totaltwo}}</text>
						</view>
						<view class="dtailedeli">
							<text>合计</text>
							<text>￥{{total}}</text>
						</view>
						<view class="dtailedeli huises">以上优惠不包含运费，实际优惠金额请以确认订单页为准</view>
						
					</view>
				</view>
			</view>
		</u-popup>
		<u-modal :show="show" @cancel="show=false" @confirm="confirmDel" title="提示" :showCancelButton="true"
			:content='content'></u-modal>
		<sheet-bottom ref="getSpecList" :isCart="isCart" :isSheet.sync="isSheet" :goodsInfo="goodsInfo"  :cartId="cartIds"
			@closeSheet="closeShee" @itemTex="onitemTex" @pricelist="onPricelist"></sheet-bottom>
	</view>
</template>

<script>
	import {
		delShopCart,
		addCollect,
		cartList,
		addOrDecGoodsNum,
		removeCartGoods,
		checkCartGoodsStatus
	} from "@/api/cart.js"
	import {
		goodsDetail,
		verifyCart
	} from "@/api/index.js"
	import sheetBottom from "@/components/sheet/sheetBottom.vue"
	import sheetRecommend from "@/components/sheet/sheetRecommend.vue"
	export default {
		data() {
			return {
				isType:1,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#fe0000'
					}
				}],
				cartList: [],
				goodsInfo:'',
				num: 1,
				isCart: 3, //是否打开购物车，1加购操作，2立即购买,3确认
				itemTexs:'',
				pricelists:{},
				isSheet: false,
				isSetmoney:true,
				isDetailed:false,
				isManager: false,
				managerText: '编辑',
				show: false,
				cart_id: '',
				cartIds:'',
				content: '是否把当前商品从购物车中移除',
				ids: [],
				isAllSelected: true, // 用来判断是否全选
				prevSelectState: [] ,// 用来保存编辑前商品的选中状态
				isCheckoutEnabled: false, // 判断结算按钮是否可用
				user_level:0 ,//判断是否为会员。0否，1是
			}
		},
		components: {
			sheetBottom,
			sheetRecommend
		},
		computed: {
			total: {
				get() {
					const money = this.cartList.reduce((prev, next) => {
						if (next.isSelect == 1) {
							prev += next.number * next.local_shop_price
						}
						return prev
					}, 0)
					return money.toFixed(2)
				},
				// set() {

				// }
			},
			totaltwo:{
				get() {
					const money = this.cartList.reduce((prev, next) => {
						if (next.isSelect == 1) {
							prev += next.number * (next.cart_market_price - next.local_shop_price)
						}
						return prev
					}, 0)
					
					return money.toFixed(2)
				},
			}
		},
		onLoad() {
			this.$nextTick(()=>{
				this.$refs.getXgjgoodlist.getRecommendlist();
			})
		},
		onShow() {
			this.getCartList();
		},
		methods: {
			//获取商品详情
			async getGoods(e,id) {
				
				this.cartIds = id;
				await goodsDetail({goods_id: e}).then(res => {
					this.goodsInfo = res.result;
					this.isCart = 3;
					this.isSheet = true;
					this.isSetmoney = false;
					this.$set(this.goodsInfo, "goods_num", 1)
						
					this.$nextTick(()=>{
						this.$refs.getSpecList.getgoodsSpecList();
					})
					
					// setTimeout(function(){
						
					// },100)
					
					
					
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
				})
			},
			//onisDetailed
			onisDetailed(){
				this.isDetailed = !this.isDetailed;
			},
			open() {
				// console.log('open');
			},
			gwc() {
				uni.navigateTo({
					url: '/package/collection/collection'
				});
			},
			fhsy() {
				uni.switchTab({
					url: '/pages/active/index'
				})
			},
			//点击左滑按钮
			chufa(e) {
				console.log(e)
				 let id = this.cartList[e.name].cart_id;
				 
				if (e.index == 0) {
					this.ids.push(id)
					//删除商品
					this.show = true;
					// this.confirmDel();
				}

			},
			//查看商品详情
			jump(id, title) {
				uni.navigateTo({
					url: '/package/info/index?id=' + id + '&title=' + title
				});
				console.log(id)
			},
			//关闭弹窗
			closeShee(e) {
				this.isSheet = e
				this.isSetmoney = true;
				// this.getCartList();
			},
			onitemTex(e){
				
				this.isSetmoney = true;
				this.cartList.forEach(item => {
					if(item.product_id == this.goodsInfo.id){
						item.dimensions = e;
					}
				  });
				// this.itemTexs = e;
			},
			onPricelist(e){
				//接受价格
				this.isSetmoney = true;
				this.cartList.forEach(item => {
					if(item.product_id == this.goodsInfo.id){
						item.local_shop_price = e.local_shop_price;
						item.market_price = e.market_price;
					}
				  });
				// this.pricelists = e;
				
			},
			//去结算
			handleSave() {
				const list = this.cartList.filter((v) => v.isSelect == 1)
				const cart_ids = list.reduce((prev, curr) => {
					prev.push(curr.cart_id)
					return prev
				}, []);
				console.log(cart_ids.join(","))
				let a = cart_ids.join(",");
				
				verifyCart({cart_ids:a}).then(res=>{
					console.log(res)
					uni.navigateTo({
						url: "/package/addOrder/index?cart_ids=" + a
					})
				}).catch(err=>{
					uni.showToast({
						title:err.msg,
						icon:'none'
					})
				})
				
				// const data = {
				// 	openid:uni.getStorageSync('openid'),
				// 	shCode:uni.getStorageSync('shCode'),
				// 	cart_ids
				// }
				// checkCartGoodsStatus(data).then(res=>{

				// 	this.$store.commit("setOrderInfo",{
				// 		orderInfo:list
				// 	})
				// 	uni.setStorageSync("orderInfo",list)
				// 	uni.navigateTo({
				// 		url:"/package/addOrder/index?order_type=1"
				// 	})
				// }).catch(err=>{
				// 	uni.showToast({
				// 		title:err.msg,
				// 		icon:"none"
				// 	})
				// })

			},
			//切换菜单
			handleManager() {
				if (this.isManager) {
					// 完成：恢复商品的选中状态和全选状态
					this.cartList.forEach((item, index) => {
						item.isSelect = this.prevSelectState[index];
					});
					this.isAllSelected = this.prevSelectAllState; // 恢复全选状态
				} else {
					// 编辑：保存当前选中状态和全选状态
					this.prevSelectState = this.cartList.map(item => item.isSelect);
					this.prevSelectAllState = this.isAllSelected; // 保存全选状态
					this.cartList.forEach(item => {
						item.isSelect = 2; // 清空所有商品的选中状态
					});
					this.isAllSelected = false; // 编辑模式下全选状态为 false
				}
				this.isManager = !this.isManager;
				this.managerText = this.isManager ? "完成" : "编辑";
				this.updateCheckoutButtonState();
				// this.isManager = !this.isManager
				// this.isManager?this.managerText = '完成':this.managerText = '编辑'
			},
			//删除购物车
			handleDelete() {
				let ids = this.cartList.filter((v) => v.isSelect == 1).map(v => v.cart_id)
				this.ids = ids
				console.log(this.ids)
				this.show = true
			},
			//确认删除
			confirmDel() {
				const data = {
					cart_ids: this.ids
				}
				console.log(data)
				delShopCart(data).then(res => {
					console.log(res)
					this.getCartList();
					this.show = false
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
					this.show = false
				})
			},
			//获取购物车列表
			getCartList() {

				cartList({}).then(res => {
					const list = res.data;
					if(list.length > 0){
						this.user_level =  res.data[0].user_level;
						this.cartList = list.map((v, i) => {
							v.isSelect = 1
							v.options = this.options
							return v
						})
						this.updateCheckoutButtonState();
					}else{
						this.cartList = list;
						this.updateCheckoutButtonState();
					}
					
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
				})
			},
			// 全选/取消全选
			toggleSelectAll() {
				console.log('触发')
				this.isAllSelected = !this.isAllSelected;
				this.cartList = this.cartList.map(item => {
					item.isSelect = this.isAllSelected ? 1 : 2; // 全选或取消全选
					return item;
				});
				this.updateCheckoutButtonState();
			},
			//点击选择
			handleSelect(item) {
				item.isSelect = item.isSelect == 1 ? 2 : 1;
				this.isAllSelected = this.cartList.every(item => item.isSelect == 1); // 检查是否全选
				this.updateCheckoutButtonState();
				/* const {isSelect,cart_id} = item
				console.log(item)
				this.cartList = this.cartList.map((v)=>{
					if(v.cart_id ==cart_id){
						isSelect==1?v.isSelect=2:v.isSelect = 1
					}
					return v
				})
				
				this.getTotal() */

			},
			//购物车加减
			changeNum(e) {
				console.log(e)
				const data = {
					cart_id: e.name,
					number: e.value
				}
				addOrDecGoodsNum(data).then(res => {
					console.log(res)
					this.cartList.filter((v) => {
						if (v.cart_id == e.name) {
							v.number = e.value
						}
					})
					// this.getTotal()


				}).catch(err => {
					let a = e.value + 1;
					console.log(a)
					console.log(this.cartList)
					this.cartList.filter((v) => {
						console.log()
						if (v.cart_id == e.name) {
							v.number = a
						}
					})
					uni.showToast({
						title: err.message,
						icon: "none"
					})
					// uni.showToast({
					// 	title:err.message,
					// 	icon:"none"
					// })
				})

			},
			//计算价格
			getTotal() {
				//计算总价
				this.total = this.cartList.reduce((prev, next) => {
					if (next.isSelect == 1) {
						prev += next.goods_num * next.product_shop_price

					}
					return prev
				}, 0)
			},
			 // 更新结算按钮的状态
			updateCheckoutButtonState() {
			  this.isCheckoutEnabled = this.cartList.some(item => item.isSelect == 1);  
			  console.log(this.isCheckoutEnabled)
			},
			//点击明细的关闭
			closeDetailed(){
				this.isDetailed = false;
			}
		}
	}
</script>

<style lang="scss">
	@import "./cart.scss";

	page {
		background-color: #f3f3f3;
	}
</style>